﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using WebUI.SmartDatingRef;
using SvcUtils;
using System.Text;

namespace WebUI {
    public partial class Search : BasePage {
        private void PerformSearch() {
            Utils.hideError(errSpan);

            int i;
            if (!int.TryParse(txtAge.Value, out i)) {
                // incorrect age
                Utils.showError(errSpan, "Возраст должен быть числом.");
                return;
            }

            // create search
            ResultWithStatusOfguid resCreate = Client.CreateSearch(SessionKeyHash);
            if (!Status.SUCCESS(resCreate.Status)) {
                Utils.showError(errSpan, Status.m(resCreate.Status));
                return;
            }
            Guid searchId = resCreate.Result;

            // add criteria
            if (chkName.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "name", 
                    s(CryptoImpl.cryptAes(bu(txtName.Value), b(SessionKey))));
            if (chkGender.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "gender",
                    s(CryptoImpl.cryptAes(bu(cboGender.Value), b(SessionKey))));
            if (chkAge.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "age",
                    s(CryptoImpl.cryptAes(bu(txtAge.Value), b(SessionKey))));
            if (chkOrientation.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "orientation",
                    s(CryptoImpl.cryptAes(bu(cboOrientation.Value), b(SessionKey))));
            if (chkReason.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "reason",
                    s(CryptoImpl.cryptAes(bu(cboReason.Value), b(SessionKey))));
            if (chkInterests.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "interests",
                    s(CryptoImpl.cryptAes(bu(txtInterests.Value), b(SessionKey))));
            if (chkBio.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "bio",
                    s(CryptoImpl.cryptAes(bu(txtBio.Value), b(SessionKey))));
            if (chkZodiac.Checked)
                Client.AddSearchCriteria(SessionKeyHash, searchId, "zodiac",
                    s(CryptoImpl.cryptAes(bu(cboZodiac.Value), b(SessionKey))));

            // get results
            ResultWithStatusOfArrayOfSearchResultswc4fAsa resSearch =
                Client.GetSearchResults(SessionKeyHash, searchId);
            rptResults.DataSource = resSearch.Result; // display them in the list

            // destroy search
            Client.DestroySearch(SessionKeyHash, searchId);

            if (!Status.SUCCESS(resSearch.Status) && resSearch.Status != OperationStatus.NoMembersFound
                && resSearch.Status != OperationStatus.NoCriteriasDefined) {
                Utils.showError(errSpan, Status.m(resSearch.Status));
                return;
            }

            ////////////////////////////////
            // display results on the map //
            string name = "";
            int gender = 2;
            PersonalData pd;
            ResultWithStatusOfstring resGetD = Client.GetPersonalData(SessionKeyHash);
            if (Status.SUCCESS(resGetD.Status)) {
                pd = CryptoImpl.readObjectEncrypted<PersonalData>(b(resGetD.Result), b(SessionKey));
                gender = pd.gender;
                name = pd.first_name + " " + pd.last_name;
            }

            // default latitude and longitude center the viewer around LETI
            const double DEFAULT_LAT = 59.97567;
            const double DEFAULT_LNG = 30.32171;
            double lat = DEFAULT_LAT, lng = DEFAULT_LNG;

            ResultWithStatusOfNullableOfPairOfdoubledoubleswc4fAsa5F2dSckg getLocRes =
                Client.GetLocation(SessionKeyHash);

            if (getLocRes.Status == OperationStatus.NoLocation) {
                // no data given for location yet.
                pnlMap.Visible = false;
            } else if (Status.SUCCESS(getLocRes.Status)) {
                // data is given, read it
                lat = getLocRes.Result.Value.First;
                lng = getLocRes.Result.Value.Second;
            } else {
                // fatal location data error
                Utils.showError(errSpan, Status.m(getLocRes.Status));
                pnlMap.Visible = false;
                return;
            }

            StringBuilder initFound = new StringBuilder("");
            if (resSearch.Result != null) {
                foreach (SearchResult r in resSearch.Result) {
                    initFound.Append("addMarkerUser({latitude:");
                    initFound.AppendFormat(new CultureInfo("en-US"), "{0}", r.latitude.HasValue ? r.latitude : DEFAULT_LAT);
                    initFound.Append(",longitude:");
                    initFound.AppendFormat(new CultureInfo("en-US"), "{0}", r.longitude.HasValue ? r.longitude : DEFAULT_LNG);
                    initFound.Append(",title:'");
                    initFound.Append(r.pd.first_name + " " + r.pd.last_name);
                    initFound.Append("',id:'");
                    initFound.Append(r.pd.usr_id.ToString());
                    initFound.Append("',gender:");
                    initFound.Append(r.pd.gender);
                    initFound.Append(",zIndex: undefined});");
                }
            }

            ScriptManager.RegisterStartupScript(this, this.GetType(), "location_init",
                "initializeMap({mapId:'map'," +
                    "txtLatId:undefined," +
                    "txtLngId:undefined," +
                    "txtNameId:undefined," +
                    "title:'" + name + "'," +
                    "gender:" + gender + "," +
                    "latitude:" + lat.ToString(new CultureInfo("en-US")) + "," +
                    "longitude:" + lng.ToString(new CultureInfo("en-US")) + "," +
                    "canMoveMyself:false});" +
                    "var initField=document.getElementById('hfInitUsers');"+
                    "if (initField.value) eval(initField.value);",
                true);
            hfInitUsers.Value = initFound.ToString();
        }

        protected void cmdSearch_Click(object sender, EventArgs e) {
            PerformSearch();
            BindAll();
        }

        private void BindAll() {
            rptResults.DataBind();
            Page.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                chkInterests.Checked = false;
                chkName.Checked = false;
                if (Request.Params["int"] != null) {
                    chkInterests.Checked = true;
                    txtInterests.Value = Request.Params["int"];
                }
                if (Request.Params["n"] != null) {
                    chkName.Checked = true;
                    txtName.Value = Request.Params["n"];
                }
                PerformSearch();
            }
            BindAll();
        }
    }
}